
import csv

import MySQLdb
import os
import glob


class MySQL:
  def __init__(self):
    try:
      self.Con = MySQLdb.connect(host="127.0.0.1", port=3336, user="root", passwd="myjsy03bjwqt", db="kylin", charset='utf8')
      self.cursor = self.Con.cursor (MySQLdb.cursors.DictCursor)
      self.cursor.execute ("set character_set_client = utf8")
      self.cursor.execute ("set character_set_connection = utf8")
      self.cursor.execute ("set character_set_results = utf8")
    except MySQLdb.Error, e:
      print "Error %d: %s" % (e.args[0], e.args[1])
      sys.exit (1)
    
  def execute(self, sql):    
    # execute and featchone
    try:
      self.cursor.execute (sql)
      result_set = self.cursor.fetchone ()
      self.cursor.execute("commit")
      return result_set
    except MySQLdb.Error, e:
      sql = sql.encode('GBK')
      err =  "sql:%s;\nMySQl--%d: %s\n" % (sql, e.args[0], e.args[1])
      print err

  def fetchone(self, sql):    
    # execute and featchone
    try:
      self.cursor.execute (sql)
      result_set = self.cursor.fetchone ()
      self.cursor.execute("commit")
      return result_set
    except MySQLdb.Error, e:
      sql = sql.encode('GBK')
      err =  "sql:%s;\nMySQl--%d: %s\n" % (sql, e.args[0], e.args[1])
      print err
      
  def fetchall(self, sql):    
    # execute and featchone
    try:
      self.cursor.execute (sql)
      result_set = self.cursor.fetchall ()
      self.cursor.execute("commit")
      return result_set
    except MySQLdb.Error, e:
      sql = sql.encode('GBK')
      err =  "sql:%s;\nMySQl--%d: %s\n" % (sql, e.args[0], e.args[1])
      print err      

def gettables():
  mysql = MySQL()
  sql = "show tables"
  all = mysql.fetchall(sql)
  tables = []
  for x in all:
    tables.append(x['Tables_in_kylin'])
  return tables
  

def getColumns(table):
  mysql = MySQL()
  sql = "show fields from %s" %(table)
  all = mysql.fetchall(sql)
  return all
  """
  for x in all:
    print x['Field'],
    print x['Type']
  """

if __name__ == "__main__":
  #tabs = gettables()
  #print tabs
  getColumns("orders")
